package com.red.wood.module.eval.mybatis.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.red.wood.common.domain.Page;
import com.red.wood.common.springjdbc.CommonDao;
import com.red.wood.common.springjdbc.SqlServerDao;
import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.IMap;
import com.red.wood.common.util.SysProps;
import com.red.wood.module.eval.mybatis.dao.EvalResultInfoDao;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class EvalResultInfoService {

	private static final Log log = LogFactory.getLog(EvalResultInfoService.class);
	
	@Autowired
	private EvalResultInfoDao dao;
	
	@Autowired
	private EvalExcelImport evalExcelImport;
	
	@Autowired
	private EvalExcelIncImport evalExcelIncImport;
	
	@Autowired
	private EvalExcelExport evalExcelExport;
	
	@Autowired
	private SqlServerDao sqlServerDao;
	
	@Autowired
	private CommonDao commonDao;
	
	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	public Map<String, Object> getPageData(IMap param) throws IOException {
		Page page = (Page) param.get("page");
		int offset = (page.getPageNo() - 1) * page.getPageSize();
		
		IMap map = sqlServerDao.getEnterpriseAuthority(param.getString("userId"));
		
		String input = IOUtils.toString(EvalResultInfoService.class.getClassLoader().getResourceAsStream("user_parser.json"),"UTF-8");
		JSONArray jArray = JSONArray.fromObject(input);
		JSONObject jsonObject = jArray.getJSONObject(0);
		
		String loginUser = CommonUtils.valueOf(map.get("loginUser"));
		int userAuthority = map.getInt("userAuthority");
		
		String province = "";
		String operator = "";
		String enterprise = "";
		
		if(userAuthority == 4) {//增值企业:不反推，对应所有
			enterprise = map.getString("realName");
		}else if(userAuthority == 5){//超级管理员
		}else {//以下都是以链路反推，查主体，然后根据链路查出来的机房名称，去机房查询对应数据和对应省份
			String value = jsonObject.getString(loginUser);
			if(userAuthority == 1) {//管局账号
				province = value;
			}else if(userAuthority == 2) {//集团账号(移动、电信、联通)
				operator = value;
			}else if(userAuthority == 3) {//省级基础电信企业(分省和运营商),如北京电信
				province = value.split("-")[0];
				operator = value.split("-")[1];
			}
		}
		int pageSize = page.getPageSize();
		param.put("userAuthority", userAuthority);
		param.put("province", province);
		param.put("operator", operator);
		param.put("enterprise",enterprise);
		param.put("pageSize", pageSize);
		param.put("offset", offset);
		
		long count = 0;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		count = dao.getCount(param);
		list = dao.getPageData(param);
		
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("totalCount", count);
		rs.put("pageData", list);
		return rs;
	}
	
	public void save(IMap params) throws Exception {
		String link_info = CommonUtils.valueOf(params.remove("link_info"));
		String house_info = CommonUtils.valueOf(params.remove("house_info"));
		
//		String sql = "select max(evalNum) evalNum from t_eval_result_query_master";
//		Map<String,Object> evalMap = jdbcTemplate.queryForMap(sql);
//		String evalNum = CommonUtils.valueOf(evalMap.get("evalNum"));
//		if(StringUtils.isBlank(evalNum)) {
//			evalNum = "AQ"+new SimpleDateFormat("yyyyMMdd").format(new Date());
//		}else {
//			long num = Long.parseLong(evalNum.substring(2, evalNum.length()))+1;
//			evalNum = "AQ" + num;
//		}
		//params.put("evalNum",evalNum);
		
		StringBuilder sqlSb = new StringBuilder("insert into t_eval_result_query_master (");
		String evalNum = CommonUtils.valueOf(params.get("evalNum"));
		String sql = "select evalNum from t_eval_result_query_master where evalNum = ?";
		List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,new Object[] {evalNum});
		if(list != null && list.size() > 0) {
			throw new Exception("当前表单编号【"+evalNum+"】已经存在！");
		}
		
		params.put("result","评测通过");
		commonDao.insertTableDataNotKey(params, sqlSb);
		
		if(StringUtils.isNotBlank(link_info)) {
			List<Map<String,Object>> linkList = new ArrayList<Map<String,Object>>();
			String[] linkSplit = link_info.split("@");
			for(String links : linkSplit) {
				Map<String,Object> map = new HashMap<String,Object>();
				String[] link = links.split("-");
				map.put("evalNum", evalNum);
				map.put("link_type", link[0]);
				map.put("link_bandwidth", link[1]);
				map.put("link_province", link[2]);
				map.put("house_name", link[3]);
				linkList.add(map);
			}
			sql = "insert into t_eval_result_query_link(evalNum,link_type,link_bandwidth,link_province,house_name) values (?,?,?,?,?)";
			String columns = "evalNum,link_type,link_bandwidth,link_province,house_name";
			commonDao.insertBatchTableData(linkList, sql, columns);
		}
		
		if(StringUtils.isNotBlank(house_info)) {
			List<Map<String,Object>> houseList = new ArrayList<Map<String,Object>>();
			String[] houseSplit = house_info.split("@");
			for(String houses : houseSplit) {
				Map<String,Object> map = new HashMap<String,Object>();
				String[] house = houses.split("-");
				map.put("evalNum", evalNum);
				map.put("house_province", house[0]);
				map.put("house_city", house[1]);
				map.put("house_name", house[2]);
				map.put("house_add", house[3]);
				houseList.add(map);
			}
			sql = "insert into t_eval_result_query_house(evalNum,house_province,house_city,house_name,house_add) values (?,?,?,?,?)";
			String columns = "evalNum,house_province,house_city,house_name,house_add";
			commonDao.insertBatchTableData(houseList, sql, columns);
		}
	}
	
	public void edit(IMap params) {
		String evalNum = CommonUtils.valueOf(params.get("evalNum"));
		String link_info = CommonUtils.valueOf(params.remove("link_info"));
		String house_info = CommonUtils.valueOf(params.remove("house_info"));
		
		StringBuilder sqlSb = new StringBuilder("update t_eval_result_query_master set ");
		String queryConf = " where evalNum='"+evalNum+"'";
		commonDao.updateTableData(params, sqlSb, queryConf);
		
		String sql = "delete from t_eval_result_query_link where evalNum='"+evalNum+"'";
		jdbcTemplate.execute(sql);
		
		sql = "delete from t_eval_result_query_house where evalNum='"+evalNum+"'";
		jdbcTemplate.execute(sql);
		
		if(StringUtils.isNotBlank(link_info)) {
			List<Map<String,Object>> linkList = new ArrayList<Map<String,Object>>();
			String[] linkSplit = link_info.split("@");
			for(String links : linkSplit) {
				Map<String,Object> map = new HashMap<String,Object>();
				String[] link = links.split("-");
				map.put("evalNum", evalNum);
				map.put("link_type", link[0]);
				map.put("link_bandwidth", link[1]);
				map.put("link_province", link[2]);
				map.put("house_name", link[3]);
				linkList.add(map);
			}
			sql = "insert into t_eval_result_query_link(evalNum,link_type,link_bandwidth,link_province,house_name) values (?,?,?,?,?)";
			String columns = "evalNum,link_type,link_bandwidth,link_province,house_name";
			commonDao.insertBatchTableData(linkList, sql, columns);
		}
		
		if(StringUtils.isNotBlank(house_info)) {
			List<Map<String,Object>> houseList = new ArrayList<Map<String,Object>>();
			String[] houseSplit = house_info.split("@");
			for(String houses : houseSplit) {
				Map<String,Object> map = new HashMap<String,Object>();
				String[] house = houses.split("-");
				map.put("evalNum", evalNum);
				map.put("house_province", house[0]);
				map.put("house_city", house[1]);
				map.put("house_name", house[2]);
				map.put("house_add", house[3]);
				houseList.add(map);
			}
			sql = "insert into t_eval_result_query_house(evalNum,house_province,house_city,house_name,house_add) values (?,?,?,?,?)";
			String columns = "evalNum,house_province,house_city,house_name,house_add";
			commonDao.insertBatchTableData(houseList, sql, columns);
		}
	}
	
	public void del(String evalNum) {
		String sql = "delete from t_eval_result_query_link where evalNum='"+evalNum+"'";
		jdbcTemplate.execute(sql);
		
		sql = "delete from t_eval_result_query_house where evalNum='"+evalNum+"'";
		jdbcTemplate.execute(sql);
		
		sql = "delete from t_eval_result_query_master where evalNum='"+evalNum+"'";
		jdbcTemplate.execute(sql);
	}
	
	public Map<String,Object> query(String evalNum){
		String sql = "select evalNum,enterprise_name,apply_business,registered_address,handleInfo,contacts,production_unit,tel,moveTle,eMail,sys_utment,result,evaluation_report,evaluation_report_name,evaluation_report_size from t_eval_result_query_master where evalNum = ?";
		Map<String,Object> masterInfo = jdbcTemplate.queryForMap(sql,evalNum);
		
		sql = "select link_province,link_type,link_bandwidth,house_name from t_eval_result_query_link where evalNum = ?";
		List<Map<String,Object>> linkInfo = jdbcTemplate.queryForList(sql,evalNum);
		
		sql = "select house_name,house_province,house_city,house_add from t_eval_result_query_house where evalNum = ?";
		List<Map<String,Object>> houseInfo = jdbcTemplate.queryForList(sql,evalNum);
		
		Map<String,Object> datas = new HashMap<String,Object>();
		datas.put("masterInfo",masterInfo);
		datas.put("linkInfo",linkInfo);
		datas.put("houseInfo",houseInfo);
		return datas;
	}
	
	public Map<String,Object> importData(MultipartFile file) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			String orgFileName = file.getOriginalFilename();
	        InputStream is = file.getInputStream();
	        String fileType = "";
	        Workbook workbook = null;
	        if(orgFileName.endsWith("xlsx")){
	            workbook = new XSSFWorkbook(is);
	            fileType = ".xlsx";
	        }else{
	            workbook = new HSSFWorkbook(is);
	            fileType = ".xls";
	        }
	        map = evalExcelImport.readExcel(workbook, fileType);    
		}catch(Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		return map;
	}
	
	public Map<String,Object> importIncData(MultipartFile file) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			String orgFileName = file.getOriginalFilename();
	        InputStream is = file.getInputStream();
	        String fileType = "";
	        Workbook workbook = null;
	        if(orgFileName.endsWith("xlsx")){
	            workbook = new XSSFWorkbook(is);
	            fileType = ".xlsx";
	        }else{
	            workbook = new HSSFWorkbook(is);
	            fileType = ".xls";
	        }
	        map = evalExcelIncImport.readExcel(workbook, fileType);    
		}catch(Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		return map;
	}
	
	public synchronized JSONObject uploadReport(MultipartFile multipartFile,String evalNum) {
		JSONObject json = new JSONObject();
    	InputStream in = null;
    	FileOutputStream out = null;
        try {
        	String originalFilename = multipartFile.getOriginalFilename();
        	String report = SysProps.getInstance().getValue("eval.report.upload.path");
    		String[] split = report.split("@");
    		StringBuffer path = new StringBuffer();
    		for(String str : split) {
    			path.append(str).append(File.separator);
    		}
        	File file = new File(path.toString());
			if (!file.exists() || !file.isDirectory()) {
				file.mkdirs();
			}
			in = multipartFile.getInputStream();
			byte[] bytes = new byte[10240];
			DecimalFormat df = new DecimalFormat("#.#");
			String size = df.format(in.available()/1024.0);
			
			//上传附件名称替换为表单编号
			String prefix = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
			
			String newFileName = evalNum+"."+prefix;
			out = new FileOutputStream(new File(file, newFileName));
			int count = 0;
			while ((count = in.read(bytes)) != -1) {
				out.write(bytes, 0, count);
			}
			
			StringBuilder sql = new StringBuilder("update t_eval_result_query_master set ");
			IMap params = new IMap();
			params.put("evaluation_report",newFileName);
			params.put("evaluation_report_name",originalFilename);
			params.put("evaluation_report_size", size);
			String queryConf = " where evalNum = '"+evalNum+"'";
			commonDao.updateTableData(params, sql, queryConf);
			
			json.put("flag",true);
			json.put("fileName", newFileName);
			json.put("originalFilename", originalFilename);
			json.put("fileSize",size);
			json.put("path",path);
			json.put("msg","上传成功");
        } catch (Exception e){
            if(log.isErrorEnabled()){
                log.error(e.getMessage(),e);
            }
            json.put("flag",false);
			json.put("msg","上传失败");
        }finally {
        	IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(in);
        } 
        return json;
    }
	
	public void reportDel(String evalNum) {
		//文件不做删除，重新上传直接覆盖即可
		String sql = "update t_eval_result_query_master set evaluation_report = null,evaluation_report_name = null,evaluation_report_size = null where evalNum = ?";
		jdbcTemplate.update(sql,evalNum);
	}
	
	public String exportData(String path,String apply_business) {
		String file_path = "";
		try {
	        String fileType = ".xlsx";
	        Workbook workbook = new XSSFWorkbook(new FileInputStream(path));
	        file_path =  evalExcelExport.readExcel(workbook, fileType,apply_business);    
		}catch(Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		}
		return file_path;
	}
}